package com.gmstu.springframework.aop.aspect;

import java.lang.reflect.Method;

/**
 * @author John.zhang
 * @version Id: GpAbstractAspectAdvice, v 1.0 2020/8/26 17:24 ZhiYong Exp $
 */
public abstract class GpAbstractAspectAdvice implements GpAdvice {

    private Method aspectMethod;

    private Object aspectTarget;

    public GpAbstractAspectAdvice(Method aspectMethod, Object aspectTarget) {
        this.aspectMethod = aspectMethod;
        this.aspectTarget = aspectTarget;
    }

    public Object invokeAdviceMethod(GpJoinPoint joinPoint, Object returnValue, Throwable throwable) throws Throwable {
        Class<?>[] parameterTypes = this.aspectMethod.getParameterTypes();
        if (null == parameterTypes || parameterTypes.length == 0) {
            return this.aspectMethod.invoke(aspectTarget);
        } else {
            Object[] args = new Object[parameterTypes.length];
            for (int i = 0; i < parameterTypes.length; i++) {
                if (parameterTypes[i] == GpJoinPoint.class) {
                    args[i] = joinPoint;
                } else if (parameterTypes[i] == Throwable.class) {
                    args[i] = throwable;
                } else if (parameterTypes[i] == Object.class) {
                    args[i] = returnValue;
                }
            }
            return this.aspectMethod.invoke(aspectTarget, args);
        }
    }


}
